<template>
  <div class="bank-card-section">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>银行卡管理</h3>
          <el-button type="primary" plain @click="showAddCardDialog">
            <el-icon><Plus /></el-icon>添加银行卡
          </el-button>
        </div>
      </template>
      
      <div class="card-list-container">
        <el-empty v-if="bankCards.length === 0" description="暂无银行卡，请添加" :image-size="100"></el-empty>
        
        <div v-else class="bank-cards-list">
          <div 
            v-for="card in bankCards" 
            :key="card.id" 
            class="bank-card-item"
            :class="[getBankClass(card.bankName), {'default-card': card.isDefault === 1}]"
          >
            <div class="card-bank-info">
              <img :src="getBankLogo(card.bankName)" alt="银行Logo" class="bank-logo">
              <span class="bank-name">{{ card.bankName }}</span>
              <el-tag v-if="card.isDefault === 1" size="small" type="success">默认</el-tag>
              <el-tag v-else size="small" type="info">普通</el-tag>
            </div>
            
            <div class="card-number">{{ formatCardNumber(card.cardNumber) }}</div>
            
            <div class="card-holder">
              <span>持卡人: {{ card.cardholderName }}</span>
              <el-tag size="small" :type="card.cardType === 1 ? 'primary' : 'warning'">
                {{ card.cardType === 1 ? '储蓄卡' : '信用卡' }}
              </el-tag>
            </div>
            
            <div class="card-actions">
              <el-button 
                v-if="card.isDefault !== 1" 
                type="text" 
                @click="setDefaultCard(card.id)"
              >设为默认</el-button>
              <el-popconfirm
                title="确定要删除此银行卡吗？"
                @confirm="deleteCard(card.id)"
              >
                <template #reference>
                  <el-button type="text" class="delete-btn">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 添加银行卡对话框 -->
    <el-dialog v-model="addCardDialogVisible" title="添加银行卡" width="500px">
      <el-form :model="cardForm" :rules="cardRules" ref="cardFormRef" label-width="100px">
        <el-form-item label="银行名称" prop="bankName">
          <el-select v-model="cardForm.bankName" placeholder="请选择银行">
            <el-option v-for="bank in bankOptions" :key="bank" :label="bank" :value="bank"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卡号" prop="cardNumber">
          <el-input v-model="cardForm.cardNumber" placeholder="请输入银行卡号"></el-input>
        </el-form-item>
        <el-form-item label="持卡人" prop="cardHolder">
          <el-input v-model="cardForm.cardHolder" placeholder="请输入持卡人姓名"></el-input>
        </el-form-item>
        <el-form-item label="卡类型" prop="cardType">
          <el-radio-group v-model="cardForm.cardType">
            <el-radio :label="1">储蓄卡</el-radio>
            <el-radio :label="2">信用卡</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="cardForm.phoneNumber" placeholder="请输入银行预留手机号"></el-input>
        </el-form-item>
        <el-form-item label="失效日期" prop="expireDate">
          <el-date-picker 
            v-model="cardForm.expireDate" 
            type="date" 
            placeholder="请选择失效日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="安全码" prop="cvv" v-if="cardForm.cardType === 2">
          <el-input v-model="cardForm.cvv" placeholder="请输入信用卡背面的3位安全码"></el-input>
        </el-form-item>
        <el-form-item label="默认卡" prop="isDefault">
          <el-switch v-model="cardForm.isDefault" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addCardDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddCard" :loading="submitLoading">添加</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, defineEmits, defineProps } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { addBankCard, setDefaultBankCard, deleteBankCard } from '@/api/account';

const props = defineProps({
  bankCards: {
    type: Array,
    default: () => []
  },
  submitLoading: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['refresh']);

// 银行卡操作相关数据
const addCardDialogVisible = ref(false);
const cardFormRef = ref(null);

// 银行卡表单数据
const cardForm = reactive({
  bankName: '',
  cardNumber: '',
  cardHolder: '',
  cardType: 1,
  phoneNumber: '',
  expireDate: '',
  cvv: '',
  isDefault: 0
});

// 银行选项
const bankOptions = [
  '工商银行', '农业银行', '中国银行', '建设银行', '招商银行', 
  '交通银行', '浦发银行', '民生银行', '中信银行', '兴业银行', 
  '光大银行', '平安银行', '邮储银行'
];

// 银行卡表单验证规则
const cardRules = {
  bankName: [
    { required: true, message: '请选择银行', trigger: 'change' }
  ],
  cardNumber: [
    { required: true, message: '请输入银行卡号', trigger: 'blur' },
    { pattern: /^\d{16,19}$/, message: '银行卡号格式不正确', trigger: 'blur' }
  ],
  cardHolder: [
    { required: true, message: '请输入持卡人姓名', trigger: 'blur' }
  ],
  cardType: [
    { required: true, message: '请选择卡类型', trigger: 'change' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  expireDate: [
    { required: true, message: '请选择失效日期', trigger: 'change' }
  ],
  cvv: [
    { pattern: /^\d{3,4}$/, message: '安全码格式不正确', trigger: 'blur' }
  ]
};

// 格式化银行卡号
const formatCardNumber = (cardNumber) => {
  if (!cardNumber) return '';
  
  // 将卡号格式化为 **** **** **** 1234 格式
  const lastFour = cardNumber.slice(-4);
  return `**** **** **** ${lastFour}`;
};

// 获取银行标识CSS类
const getBankClass = (bankName) => {
  if (!bankName) return '';
  
  const bankMap = {
    '工商银行': 'icbc-card',
    '农业银行': 'abc-card',
    '中国银行': 'boc-card',
    '建设银行': 'ccb-card',
    '招商银行': 'cmb-card',
    '交通银行': 'bocom-card',
    '浦发银行': 'spdb-card',
    '民生银行': 'cmbc-card',
    '中信银行': 'citic-card',
    '兴业银行': 'cib-card',
    '光大银行': 'ceb-card',
    '平安银行': 'pab-card',
    '邮储银行': 'psbc-card'
  };
  
  return bankMap[bankName] || 'default-bank-card';
};

// 获取银行LOGO
const getBankLogo = (bankName) => {
  // 在实际项目中，这里应该返回银行logo的URL
  // 这里简化处理，返回一个通用图标
  return 'https://img.icons8.com/color/48/000000/bank-building.png';
};

// 显示添加银行卡对话框
const showAddCardDialog = () => {
  // 重置表单
  cardForm.bankName = '';
  cardForm.cardNumber = '';
  cardForm.cardHolder = '';
  cardForm.cardType = 1;
  cardForm.phoneNumber = '';
  cardForm.expireDate = '';
  cardForm.cvv = '';
  cardForm.isDefault = props.bankCards.length === 0 ? 1 : 0; // 如果没有银行卡，默认设为默认卡
  
  // 显示对话框
  addCardDialogVisible.value = true;
};

// 处理添加银行卡
const handleAddCard = async () => {
  if (!cardFormRef.value) return;
  
  await cardFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await addBankCard({
          bankName: cardForm.bankName,
          cardNumber: cardForm.cardNumber,
          cardHolder: cardForm.cardHolder,
          cardType: cardForm.cardType,
          phoneNumber: cardForm.phoneNumber,
          expireDate: cardForm.expireDate,
          cvv: cardForm.cvv,
          isDefault: cardForm.isDefault
        });
        
        if (response.code === 0) {
          ElMessage.success('银行卡添加成功');
          addCardDialogVisible.value = false;
          
          // 通知父组件刷新银行卡列表
          emit('refresh');
        }
      } catch (error) {
        console.error('添加银行卡失败:', error);
        ElMessage.error('添加银行卡失败，请重试');
      }
    }
  });
};

// 设置默认银行卡
const setDefaultCard = async (cardId) => {
  try {
    const response = await setDefaultBankCard(cardId);
    
    if (response.code === 0) {
      ElMessage.success('默认银行卡设置成功');
      
      // 通知父组件刷新银行卡列表
      emit('refresh');
    }
  } catch (error) {
    console.error('设置默认银行卡失败:', error);
    ElMessage.error('设置默认银行卡失败，请重试');
  }
};

// 删除银行卡
const deleteCard = async (cardId) => {
  try {
    const response = await deleteBankCard(cardId);
    
    if (response.code === 0) {
      ElMessage.success('银行卡删除成功');
      
      // 通知父组件刷新银行卡列表
      emit('refresh');
    }
  } catch (error) {
    console.error('删除银行卡失败:', error);
    ElMessage.error('删除银行卡失败，请重试');
  }
};
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.bank-cards-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 10px;
}

.bank-card-item {
  background: linear-gradient(135deg, #e0e0e0, #f5f5f5);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: relative;
  transition: transform 0.3s, box-shadow 0.3s;
}

.bank-card-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.default-card {
  background: linear-gradient(135deg, #e6f7ff, #f0f9ff);
  border: 1px solid #1890ff;
}

/* 各银行卡样式 */
.icbc-card {
  background: linear-gradient(135deg, #d10f19, #f54e59);
  color: white;
}

.abc-card {
  background: linear-gradient(135deg, #1e9e3e, #5cc977);
  color: white;
}

.boc-card {
  background: linear-gradient(135deg, #a72126, #d4484d);
  color: white;
}

.ccb-card {
  background: linear-gradient(135deg, #0066b3, #4a9fdd);
  color: white;
}

.cmb-card {
  background: linear-gradient(135deg, #a51220, #d4484d);
  color: white;
}

.bocom-card {
  background: linear-gradient(135deg, #004098, #4a7ac9);
  color: white;
}

.spdb-card {
  background: linear-gradient(135deg, #0c4da2, #4a7ac9);
  color: white;
}

.cmbc-card {
  background: linear-gradient(135deg, #1c4e9c, #5b82ce);
  color: white;
}

.citic-card {
  background: linear-gradient(135deg, #c7000a, #f54e59);
  color: white;
}

.cib-card {
  background: linear-gradient(135deg, #0159a0, #4a9fdd);
  color: white;
}

.ceb-card {
  background: linear-gradient(135deg, #f47d20, #f8a563);
  color: white;
}

.pab-card {
  background: linear-gradient(135deg, #ef5b24, #f8a563);
  color: white;
}

.psbc-card {
  background: linear-gradient(135deg, #007f3e, #5cc977);
  color: white;
}

.default-bank-card {
  background: linear-gradient(135deg, #424242, #757575);
  color: white;
}

.card-bank-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.bank-logo {
  width: 24px;
  height: 24px;
}

.bank-name {
  font-weight: 600;
  flex: 1;
}

.card-number {
  font-size: 18px;
  letter-spacing: 2px;
  margin-bottom: 15px;
}

.card-holder {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.delete-btn {
  color: #f56c6c;
}

@media (max-width: 768px) {
  .bank-cards-list {
    grid-template-columns: 1fr;
  }
}
</style>
